package luj.tool.jnproxyan.framework.lujnet.connect;

import luj.bean.api.BeanContext;
import luj.bean.api.bean.Bean;
import luj.cluster.api.actor.Tellable;
import luj.net.api.server.ConnectionAcceptInitializer;
import luj.tool.jnproxyan.framework.lujnet.BindParam;
import luj.tool.jnproxyan.framework.lujnet.ConnState;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.message.request.init.add.AddRequestMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 浏览器发起一个网页请求
 */
@Component
final class OnAcceptInit implements ConnectionAcceptInitializer {

  /**
   * @see luj.tool.jnproxyan.framework.lujcluster.OnLujclusterStart
   * @see luj.tool.jnproxyan.framework.lujnet.receive.Recv31Start#receive
   */
  @Override
  public Object init(Context ctx) {
    Connection conn = ctx.getConnection();
    long now = System.currentTimeMillis();

    Long reqId = _nextReqId.getAndIncrement();
    LOG.debug("浏览器新请求：#{}", reqId);

    Bean<AddRequestMsg> msg = _lujbean.createBean(AddRequestMsg.class);
    msg.setField(m -> m::reqId, reqId);
    msg.setField(m -> m::time, now);
    msg.setField(m -> m::c2pConn, conn);

    BindParam param = ctx.getBindParam();
    Tellable socksRef = param.getSocksRef();
    socksRef.tell(msg.getValueInstance());

    return new ConnState(reqId, socksRef, conn);
  }

  private static final Logger LOG = LoggerFactory.getLogger(OnAcceptInit.class);

  AtomicLong _nextReqId = new AtomicLong(1);

  @Autowired
  BeanContext _lujbean;
}
